declare var wx;
export default class Utils {
    private static _vvid = ""

    //查找数组里是否包含某个元素
    public static IsContainElement(arr, item) {
        if (arr) {
            for (var i = 0; i < arr.length; i++) {
                if (arr[i] == item) {
                    return true;
                }
            }
        }
        return false;
    };

    //从一个数组里随机取一个元素
    public static RandomElement(arr) {
        if (arr) {
            var len = arr.length;

            var minIndex = 0;
            var maxIndex = len - 1;

            var index = this.RandomNum(minIndex, maxIndex);

            return arr[index];
        }

        return null;
    };

    //深拷贝数组
    public static CopyArray(arr) {
        return arr.concat();
    };

    //是否为数字 包括字符串数字
    public static IsNumber(val) {

        var regPos = /^\d+(\.\d+)?$/; //非负浮点数
        var regNeg = /^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$/; //负浮点数
        if (regPos.test(val) || regNeg.test(val)) {
            return true;
        } else {
            return false;
        }
    };

    //根据传入的最大字符个数截取字符串
    public static GetByteVal(val, max) {
        var returnValue = '';
        var byteValLen = 0;
        for (var i = 0; i < val.length; i++) {
            if (val[i].match(/[^\x00-\xff]/ig) != null)
                byteValLen += 2;
            else
                byteValLen += 1;
            if (byteValLen > max)
                break;
            returnValue += val[i];
        }
        return returnValue;
    };


    public static IsString(val) {
        return typeof (val) == "string";
    };

    public static IsObject(val) {
        return (typeof (val) == "object") && ((val instanceof Array) == false);
    };

    //从数组里移除一个元素
    public static RemoveItem(arr, item) {
        if (this.IsArray(arr)) {
            for (var i = 0; i < arr.length; i++) {
                if (arr[i] == item) {
                    arr.splice(i, 1);
                    return;
                }
            }
        }
    };

    public static GetPrefab(path, cb = null, thisobj = null) {
        cc.loader.loadRes(path, cc.Prefab, (err, prefab) => {
            cb && cb.apply(thisobj, [prefab]);
        });
    };

    //设置精灵节点的图片
    public static SetNodeTexture(node, filename, cb, thisobj) {
        var sprite = node.getComponent(cc.Sprite);
        if (sprite) {
            cc.loader.loadRes(filename, cc.SpriteFrame, (err, spriteFrame) => {
                sprite.spriteFrame = spriteFrame;
                cb && cb.apply(thisobj);
            });
        }
    };

    //
    public static SetNodeSprteFrame(node, spriteFrame) {
        var sprite = node.getComponent(cc.Sprite);
        if (sprite) {
            sprite.spriteFrame = spriteFrame;
        }
    }

    //设置文本节点的内容
    public static SetNodeText(node, text) {
        if (node) {
            if (this.IsNumber(text) || this.IsString(text)) {
                var label = node.getComponent(cc.Label);
                if (label) {
                    label.string = text;
                }
            }
        }
    };

    public static LoadHeadImg(node, url) {
        console.log("下载头像" + url)
        if (!url) {
            return;
        }
        cc.loader.load({
            url: url, type: 'jpeg'
        }, (err, texture) => {
            if (err) {
                debugger;
            }
            if (texture) {
                node.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(texture);
                node.getComponent(cc.Sprite).spriteFrame.width = node.width;
                node.getComponent(cc.Sprite).spriteFrame.height = node.height;
            }
        });
    };

    public static CreateSprite(name, texture, cb: Function, thisobj) {
        var node = new cc.Node(name);
        node.anchorX = node.anchorY = 0.5;
        if (node) {
            cc.loader.loadRes(texture, cc.SpriteFrame, (err, spriteFrame) => {
                var sprite = node.addComponent(cc.Sprite);
                sprite.spriteFrame = spriteFrame;
                cb && cb.apply(thisobj, [node]);
            });
        }
    }

    public static CreateSpriteWithFrame(name, spriteFrame) {
        var node = new cc.Node(name);
        if (node) {
            var sprite = node.addComponent(cc.Sprite);
            sprite.spriteFrame = spriteFrame;
            return node;
        }
        return null;
    }


    /**
     * 载入单个资源
     * - 输出log
     * @param path 
     * @param type 
     * @static
     */
    static load_res<T extends typeof cc.Asset>(path: string, type: T): Promise<InstanceType<T>> {
        return new Promise(res => {
            cc.loader.loadRes(path, type, (err, resource) => {
                if (err) {
                    cc.error(`resource load fail, path=${path}, type=${type}, error=${err}`)
                    res(null)
                } else {
                    res(resource)
                }
            })
        })
    }

    //获取指定节点的指定组件
    public static GetComponent(node, component) {
        if (node && component) {
            return node.getComponent(component);
        }
        return null;
    }

    //添加组件
    public static AddComponent(node, component) {
        if (node && component) {
            return node.addComponent(component);
        }
        return null;
    };

    //移除组件
    public static RemoveComponent(node, component) {
        if (node && component) {
            node.removeComponent(component);
        }
    };

    public static SetWidgetTarget(node, target) {
        if (node && target) {
            var widgetCom = node.getComponent(cc.Widget);
            if (widgetCom) {
                widgetCom.target = target;
            }
        }
    }

    //添加序列帧特效
    public static AddAutoRemoveEffect(node, prefabPath, name, cb, thisobj, cb1 = null) {
        if (node && prefabPath) {
            cc.loader.loadRes(prefabPath, cc.Prefab, (err, prefab) => {
                if (prefab) {
                    var Anim_Node = cc.instantiate(prefab);
                    Anim_Node.x = node.x;
                    Anim_Node.y = node.y;
                    Anim_Node.zIndex = node.zIndex + 1;
                    Anim_Node.parent = node.parent;
                    var anim = this.GetComponent(Anim_Node, cc.Animation);
                    if (anim) {
                        cb1 && cb1.apply(thisobj);
                        anim.play(name);
                        anim.on('finished', () => {
                            Anim_Node.destroy();
                            cb && cb.apply(thisobj);
                        });
                    }
                }
            });
        }
    }


    //添加骨骼动画
    public static AddAutoRemoveDragonBone(node, prefabPath, name, cb, thisobj, cb1 = null) {
        if (node && prefabPath) {
            cc.loader.loadRes(prefabPath, cc.Prefab, (err, prefab) => {
                if (prefab) {
                    var Anim_Node = cc.instantiate(prefab);
                    Anim_Node.x = node.x;
                    Anim_Node.y = node.y;
                    Anim_Node.zIndex = node.zIndex + 1;
                    Anim_Node.parent = node.parent;
                    var anim = Anim_Node.getComponent("Burst");
                    if (anim) {
                        cb1 && cb1.apply(thisobj);
                        anim.play();
                        anim.node.on('finished', () => {
                            Anim_Node.destroy();
                            cb && cb.apply(thisobj);
                        });
                    }
                }
            });
        }
    }

    //注册按钮点击事件
    public static addEventListener(button, callback) {
        // cc.assert(button, "button is null");
        // cc.assert(callback, "callback is null");

        if (button && callback) {
            button.on(cc.Node.EventType.TOUCH_START, callback);
        }
    }

    //取消按钮的点击事件
    public static removeEventListener(button) {
        if (button) {
            button.off(cc.Node.EventType.TOUCH_START);
        }
    }

    //注册按钮点击事件
    public static RegTouchEndEvent(button, callback) {
        if (button && callback) {
            button.on(cc.Node.EventType.TOUCH_END, callback);
        }
    }

    public static SetButtonInteractable(btn, interactable) {
        if (btn) {
            var com = btn.getComponent(cc.Button);
            if (com) {
                com.interactable = interactable;
            }
        }
    };


    //注册键盘按下事件
    public static RegKeyUpEvent(callback) {
        if (callback) {
            cc.systemEvent.on(cc.SystemEvent.EventType.KEY_UP, callback);
        }
    }

    public static RegBtnTouchBeginEvent(button, callback) {
        if (button && callback) {
            button.on(cc.Node.EventType.TOUCH_START, callback);
        }
    }



    //屏幕适配
    public static ScreenAdaptation(node) {
        // if(node){
        //     if(cc.director.getWinSize().height / cc.director.getWinSize().width - 16 / 9 > 0.1){ 
        //         node.scale = cc.director.getWinSize().width / 750;
        //     }
        // }
    }

    public static Sort(arr) {
        var compare = function (x, y) {
            if (x < y) {
                return 1;
            } else if (x > y) {
                return -1;
            } else {
                return 0;
            }
        };

        arr.sort(compare);
    }

    //根据gid对节点进行排序
    public static NodeSort(arr) {
        var compare = function (node_a, node_b) {
            if (node_a.gid < node_b.gid) {
                return 1;
            } else if (node_a.gid > node_b.gid) {
                return -1;
            } else {
                return 0;
            }
        };

        arr.sort(compare);
    }

    public static RandomNum(min, max) {
        return parseInt(Math.random() * (max - min + 1) + min, 10);
    }

    public static GetDistance(p1, p2) {
        return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
    }

    public static IsArray(obj) {
        return typeof obj == 'object' && obj.constructor == Array;
    }

    //去重
    public static RemoveDuplicate(arr) {
        if (this.IsArray(arr)) {
            var newArr = [];
            for (var i = 0; i < arr.length; i++) {
                if (newArr.indexOf(arr[i]) < 0) {
                    newArr.push(arr[i]);
                }
            }
            return newArr;
        }
        return arr;
    }

    //去掉包含在arr2中的元素
    public static RemoveDuplicateArray(arr1, arr2) {
        if (this.IsArray(arr1) && this.IsArray(arr2)) {
            var newArr = [];
            for (var j = 0; j < arr2.length; j++) {
                var index = arr1.indexOf(arr2[j]);
                if (index >= 0) {
                    arr1.splice(index, 1);
                }
            }
            return newArr;
        }
    };

    //根据指定的概率返回true
    public static RandomPercentage(percentile) {
        var value = this.RandomNum(1, 100);

        if (value <= percentile) {
            return true;
        }
        return false;
    };


    public static loadRemoteImg(node, url) {
        cc.loader.load({
            url: url, type: 'jpg'
        }, (err, texture) => {
            node.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(texture);
        });
    };

    public static loadBase64Image(strImg: string, parent: cc.Node): void {
        let img = new Image();
        img.src = strImg;
        let texture = new cc.Texture2D();
        texture.initWithElement(img);
        texture.width = parent.width;
        texture.height = parent.height;
        img.onload = () => {
            cc.error(1221111111111111111111111111111111111111);
            texture.handleLoadedTexture();
            parent.getComponent(cc.Sprite).spriteFrame = new cc.SpriteFrame(texture);
        }
    }

    /**
     * 名字框那里 如果超出10个字符 就用...代替
     * @param inset 
     */
    public static cutNick(inset: string): string {
        let out = ""
        let len = 0;
        for (let i = 0; i < inset.length; i++) {
            if (inset.charCodeAt(i) > 127 || inset.charCodeAt(i) == 94) {
                len += 2;
            } else {
                len++;
            }
            out += inset[i];
            if (len >= 10) {
                out += "..."
                break;
            }
        }
        return out;
    }
    /**
     * 传入长度，生成指定长度随机字符串
     * @param len 
     * @returns 
     */
    public static _randomString = (len) => {
        let e = (len && len > 0) ? len : 32;
        const t = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789"
        let a = t.length
        let n = "";
        for (let i = 0; i < e; i++) {
            n += t.charAt(Math.floor(Math.random() * a));
        }
        return n
    }
    /**
     * 生成一个随机数用来作为uuRequesiId
     * @returns 
     */
    public static createUURequrstId = () => {
        const reqTime = new Date().getTime();
        const uuRequestId = Utils._randomString(16) + reqTime
        return uuRequestId
    }



    /**
     * 有则返回已有uuid,无则创建并返回uuid
     * @returns 
     */
    public static _newUuid = () => {
        if(cc.sys.platform !== cc.sys.WECHAT_GAME){
            return Utils._randomString(32) + new Date().getTime();
        }
        let uuid = wx.getStorageSync("uuid")
        if (uuid) {
            return uuid
        } else {
            uuid = Utils._randomString(32) + new Date().getTime();
            wx.setStorageSync("uuid", uuid)
        }
        return uuid;
    }
    /**
     * 有则返回已有vvid,无则创建并返回vvid
     * @returns 
     */
    public static _newVvid = () => {
        if (Utils._vvid) {
            return this._vvid
        } else {
            Utils._vvid = Utils._randomString(32) + new Date().getTime();
        }
        return Utils._vvid;
    }

}